package decorator

import "fmt"

// 实际业务场景：订单处理系统
// 假设我们有一个电商订单处理系统，需要动态添加各种处理步骤：
// 基础订单处理
// 添加折扣计算
// 添加物流保险
// 添加......可以继续扩展装饰器类


// OrderProcessor 组件接口
type OrderProcessor interface {
	ProcessOrder() string
	CalculateCost() float64
}

// BasicOrder 具体组件-基础订单
type BasicOrder struct {
	Items []struct {
		Name     string
		Price    float64
		Quantity int
	}
}

func NewBasicOrder() *BasicOrder {
	return &BasicOrder{Items: []struct {
		Name     string
		Price    float64
		Quantity int
	}{
		{Name: "MacBook Pro", Price: 100.0, Quantity: 1},
		{Name: "AirPods Pro", Price: 50.0, Quantity: 3},
	}}
}

func (r *BasicOrder) ProcessOrder() string {
	result := "基础订单处理:\n"
	total := 0.0
	for _, item := range r.Items {
		itemTotal := item.Price * float64(item.Quantity)
		result += fmt.Sprintf("- %s x%d: ￥%.2f\n", item.Name, item.Quantity, itemTotal)
		total += itemTotal
	}
	result += fmt.Sprintf("订单总金额: ￥%.2f\n", total)
	return result
}

func (r *BasicOrder) CalculateCost() float64 {
	var totalCost float64
	for _, item := range r.Items {
		totalCost += item.Price * float64(item.Quantity)
	}
	return totalCost
}

// OrderDecorator 装饰器基类
type OrderDecorator struct {
	processor OrderProcessor
}

func NewOrderDecorator(orderProcessor OrderProcessor) *OrderDecorator {
	return &OrderDecorator{processor: orderProcessor}
}

func (d *OrderDecorator) ProcessOrder() string {
	return d.processor.ProcessOrder()
}

func (d *OrderDecorator) CalculateCost() float64 {
	return d.processor.CalculateCost()
}

// === 具体装饰器

// DiscountDecorator 折扣装饰器
type DiscountDecorator struct {
	*OrderDecorator
	discountRate float64	//折扣率
}

func NewDiscountDecorator(orderProcessor OrderProcessor, discountRate float64) *DiscountDecorator {
	return &DiscountDecorator{
		OrderDecorator: NewOrderDecorator(orderProcessor),
		discountRate:   discountRate,
	}
}

func (d *DiscountDecorator) ProcessOrder() string {
	// 添加折扣信息
	base := d.processor.ProcessOrder()
	original := d.processor.CalculateCost()
	discounted := original * (1 - d.discountRate/100)
	return base + fmt.Sprintf("应用 %.0f%% 折扣: -¥%.2f\n", d.discountRate, original-discounted)
}

func (d *DiscountDecorator) CalculateCost() float64 {
	// 计算折扣后的总价
	original := d.processor.CalculateCost()
	return original * (1 - d.discountRate/100)
}

// ShippingDecorator 物流保险装饰器
type ShippingDecorator struct {
	*OrderDecorator
	shippingCost float64
}

func NewShippingDecorator(orderProcessor OrderProcessor, shippingCost float64) *ShippingDecorator {
	return &ShippingDecorator{
		OrderDecorator: NewOrderDecorator(orderProcessor),
		shippingCost:   shippingCost,
	}
}

func (d *ShippingDecorator) ProcessOrder() string {
	// 添加物流保险信息
	result := d.processor.ProcessOrder()
	return result + fmt.Sprintf("添加物流保险: ￥%.2f\n", d.shippingCost)
}

func (d *ShippingDecorator) CalculateCost() float64 {
	// 计算添加物流保险后的总价
	original := d.processor.CalculateCost()
	return original + d.shippingCost
}
